package ee.dmitri.gogetsomerest;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * @author p998msi
 */
public class MainWindow extends JFrame {

  public static final long REST_INTERVAL = 8 * 60 * 1000; // 8 min

  public MainWindow() throws HeadlessException {
    super("Go Get Some Rest!");

    init();

    setLayout(new BorderLayout());
    TimerPane timerPane = new TimerPane();
    add(timerPane, BorderLayout.CENTER);
    addKeyListener(new EscKeyListener());
  }

  public static void main(String[] args) {
    MainWindow mainWindow = new MainWindow();
    mainWindow.setVisible(true);
  }

  private void init() {
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setSize(400, 400);
    setResizable(false);
    setLocationRelativeTo(null);
  }

  public static class TimerPane extends JLabel {

    public static final long MS_IN_MIN = 60 * 1000;

    public TimerPane() {
      init();
      new LabelUpdater(REST_INTERVAL, this).start();
    }

    private void init() {
      setHorizontalAlignment(CENTER);
      setFont(new Font("Sans", Font.PLAIN, 80));
      setTimeLabel(REST_INTERVAL);
    }

    public void setTimeLabel(long time) {
      long minutes = time / MS_IN_MIN;
      long seconds = (time - minutes * MS_IN_MIN) / 1000;
      setText(String.format("%02d:%02d", minutes, seconds));
    }

  }

  public static class LabelUpdater extends Thread {

    public static final long SLEEP_TIME = 1000; // 1 second
    private TimerPane label;
    private long time;

    public LabelUpdater(long time, TimerPane label) {
      this.label = label;
      this.time = time;
    }

    public void run() {

      while (!interrupted()) {
        try {
          sleep(SLEEP_TIME);
          time -= SLEEP_TIME;
          label.setTimeLabel(time);
          if (time <= 0) {
            label.setText("Go back to work!");
            System.exit(0);
          }
        }
        catch (InterruptedException ignored) {
          Thread.currentThread().interrupt();
        }
      }

    }

  }

  public static class EscKeyListener extends KeyAdapter {

    @Override
    public void keyReleased(KeyEvent keyEvent) {
      if (keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE) {
        System.exit(0);
      }
    }

  }


}
